<template>
  <div ref="contentContainer" class="content-container">
    
    <el-scrollbar
      class="content-component__scroll"
    >
      

      <!-- 富文本编辑器 -->
      <div class="rich-text-wrap">
        <!-- 标题 -->
        <el-input
            type="text"
            class="article-title"
            placeholder="请输入文章标题(5-30个汉字)"
            v-model="setting.title"
            maxlength="30"
            show-word-limit
        >
        </el-input>

        <div class="rich-text">
          <quill-editor 
            v-model="setting.content" 
            ref="myQuillEditor" 
            :options="editorOption" 
            @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
            @change="onEditorChange($event)">

          </quill-editor>
        </div>

      </div>


      <!-- 文章发布设置 -->
      <div class="article-setting-wrap">
        
        <el-form
           class="setting-form"
          :model="setting"
          label-width="120px"

        >
          <el-form-item label="文章分类">
            
              <el-select v-model="setting.categoryId" clearable placeholder="请选择文章分类">
                <el-option
                  v-for="item in articleCata"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>

          </el-form-item>


          <el-form-item label="封面">
            
              <el-radio-group 

                v-model="setting.cover"
                text-color="#ff8100"
                @change="thumNumChange"
              >
                <el-radio label="1">单图</el-radio>
                <el-radio label="2">三图</el-radio>
                <el-radio label="3">无图</el-radio>
              </el-radio-group>

              <div class="thum-wrap" v-show="setting.cover != 3">

                <div 
                  v-for="(thum,key) in saveThumId"  
                  :key="key"
                  v-show="setting.cover == 1 ? key<1 : setting.cover == 2 ? key < 3 : key < 0" 
                  class="thum-item" 
                  @click="selectThum">
                  <div v-if="thum" class="thum-img-wrap">
                    <img :src="imgPrefix+thum">
                  </div>
                  <i v-if="!thum" class="el-icon-plus"></i>
                </div>
              </div>

          </el-form-item>


          <el-form-item label="设置">
            
              <el-radio-group 
                v-model="setting.advertising"
                text-color="#ff8100"
                @change="advsChange"
              >
                <el-radio label="1">投放广告</el-radio>
                <el-radio label="0">不投放广告</el-radio>
              </el-radio-group>

          </el-form-item>

          <el-form-item label="售卖方式">
            
              <el-radio-group 
                v-model="setting.saleWay"
                text-color="#ff8100"
                @change="saleTypeChange"
              >
                <el-radio :label="1">付费</el-radio>
                <el-radio :label="2">免费</el-radio>
                <el-radio :label="3">原创</el-radio>
              </el-radio-group>

          </el-form-item>


          <el-form-item label="商品价格">
            
              <el-input v-model="setting.goodsPrice"></el-input>
              <span>元</span>
          </el-form-item>
          
          <el-form-item label="阅读百分比">
            
              <el-input v-model="setting.readPercent"></el-input>

          </el-form-item>

          <!-- 发布账号 -->
          <el-form-item label="账号">
            
              <select-account></select-account>

          </el-form-item>

        </el-form>

      </div>

      
      <!-- 操作栏 -->
      <div ref="footer" class="footer">
        <div class="footer-contain">
          <el-button type="primary" @click="saveHandler(1)">发表</el-button>
          <el-button @click="saveHandler(5)">定时发表</el-button>
          <el-button @click="savePreview(3)">保存并预览</el-button>
          <el-button @click="saveHandler(3)">存为草稿</el-button>
        </div>
      </div>


    </el-scrollbar>


    
    <!-- 图片添加模态框组件 -->
    <upload-dialog
      :visible.sync="uploadDialogVisible"
      @close="uploadDialogClose"
      @confirm="insertImgToContent"
    ></upload-dialog>


    <!-- 选择缩略图 -->
    <select-thum
      :visible.sync="thumDialog"
      :data.sync="cacheImgs"
      :type.sync="setting.cover"
      :default-select="saveThumId"
      @close="thumSelectClose"
      @confirm="thumSelectConfirm"
    ></select-thum>


    <!-- 定时发表 -->
    <publish-time-dialog
      :visible="setTimingDialog"
      @cancel="publishTimeCancel"
      @comfirm="publishTimeComfirm"
    ></publish-time-dialog>

  </div>

</template>

<script>
import { mapGetters } from 'vuex'
import { save, getMaterialList, getImgInfo, getArticleDetail } from "@/api/substance/publish"
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import Quill from 'quill'

/*创建自定义图片*/
const Embed = Quill.import('blots/block/embed');

class IpcImage extends Embed{
  static create(value){
    let node = super.create();
    IpcImage.buildDiv(value,node)
    return node
  }

  static value(node) {
    return node.dataset.src;
  }

  static buildDiv(value,node){
    node.setAttribute('data-name', 'ipc-image');
    node.setAttribute('data-src', value);
    Object.assign(node.style,{
      textAlign:'center',
      lineHeight:'0',
      margin:'20px 0'
    });
    let image = document.createElement('img');
    image.setAttribute('width',440);
    image.setAttribute('src',value);

    node.appendChild(image)

  }
}


IpcImage.blotName = 'ipcImage';
IpcImage.className = 'ql-ipace-image';
IpcImage.tagName = 'div';


Quill.register(IpcImage)


import UploadDialog from './uploadDialog';
import PublishTimeDialog from "@/components/dingNiu/publishTimeDialog";
import SelectAccount from './selectAccount';
import SelectThum from './selectThum';

import { getList } from "@/api/substance/articleTag"
import { deepClone, getNowStr } from "@/utils/util"
import { baseUrl } from '@/config/env';
import { validatenull } from "@/utils/validate"


//定义富文本工具栏标题
const titleConfig = {
    "ql-bold": "加粗" ,
      "ql-color": "颜色",
      "ql-font": "字体",
      "ql-code": "插入代码",
      "ql-italic": "斜体",
      "ql-link": "添加链接",
      "ql-background": "背景颜色",
      "ql-size": "字体大小",
      "ql-strike": "删除线",
      "ql-script": "上标/下标",
      "ql-underline": "下划线",
      "ql-blockquote": "引用",
      "ql-header": "标题",
      "ql-indent": "缩进",
      "ql-list": "列表",
      "ql-align": "文本对齐",
      "ql-direction": "文本方向",
      "ql-code-block": "代码块",
      "ql-formula": "公式",
      "ql-image": "图片",
      "ql-video": "视频",
      "ql-clean": "清除字体样式",
      "ql-upload": "文件",
      "ql-customImage": "上传图片"
};


//获取图片的url
const imgPrefix = baseUrl+'/rest/common/preview/';

export default {
    components: {
      quillEditor,
      PublishTimeDialog,
      UploadDialog,
      SelectThum,
      SelectAccount
    },
    computed:{
      
    },
    data() {
        var _this = this;
        return {
            //上传图片dialog
            uploadDialogVisible:false,
            //添加缩略图dialog
            thumDialog:false,
            //定时发表模态框
            setTimingDialog:false,

            //服务器图片前缀
            imgPrefix:imgPrefix,

            //正文图片插入缓存列表
            cacheImgs:[],
            //保存的缩略图id
            saveThumId:[],
            defaultSetting:{
              title:'',
              categoryId:'',
              cover:'-1',
              converIds:'',
              advertising:'-1',
              saleWay:-1,
              goodsPrice:'',
              subscribe:0,
              readPercent:'',
              updateTime:'',
              status:1,
              publishTime:'',
              content:''
            },
            //文章设置
            setting:{
              title:'',
              categoryId:'',
              cover:'-1',
              converIds:'',
              advertising:'-1',
              saleWay:-1,
              goodsPrice:'',
              subscribe:0,
              readPercent:'',
              updateTime:'',
              status:1,
              publishTime:'',
              content:''
            },
            //内容容器样式
            contentStyObj:null,
            footerStyObj:null,
            //loginByPhone
            articleCata:[],
            editorOption: {
              placeholder: '请输入正文',
              modules:{
                toolbar:{
                  container:[
                    ['bold','italic','underline','strike'],
                    ['blockquote','code-block'],
                    [{'header':1},{'header':2}],
                    [{'list':'ordered'},{'list':'bullet'}],
                    [{'script':'sub'},{'script':'super'}],
                    [{'indent':'-1'},{'indent':'+1'}],
                    [{'direction':'rtl'}],
                    [{'size':['small',false,'large','huge']}],
                    [{'header':[1,2,3,4,5,6,false]}],
                    [{'color':[]},{'background':[]}],
                    [{'font':[]}],
                    [{'align':[]}],
                    ['clean'],
                    ['customImage']
                  ],
                  handlers:{
                    shadeBox:null,
                    customImage:function(){
                      _this.uploadDialogVisible = true
                    }
                  }

                }

              }

            },
            //富文本当前指针信息
            addRange:[],

            userInfo:null,

        }
    },
    created(){

    },
    mounted(){

      //alert(this.$refs.contentContainer.offsetWidth)
      
      this.setSize();
      this.getArticleCata();
      this.getUserInfo();
      //添加富文本工具栏标题
      this.addQuillTitle();
      this.initButton();

      //判断是否有articleId,如果有就是编辑
      this.isEdit();
    },
    methods: {
        //编辑还是添加
        isEdit(){
          
          var articleId = this.$route.query.articleId;
          if(articleId !== undefined){
            //请求文章详情参数
            getArticleDetail(articleId).then((res)=>{
              console.log("-------获取文章详情----------")
              console.log(res)
              this.setting = res.data.data;
              //设置缩略图
              this.saveThumId = this.setting.converIds.split(',');
            })
          }
        },
        //获取用户信息
        getUserInfo(){
          this.$store.dispatch('user/GetUserInfo').then((userInfo)=>{
            console.log("------publish-获取用户信息------")
            console.log(userInfo);
            this.userInfo = userInfo;

          });
        },
        //设置元素的css属性
        setSize(){
          var containerWidth = this.$refs.contentContainer.offsetWidth;
          var footerHeight = this.$refs.footer.offsetHeight;

          this.contentStyObj = {
            'marginBottom':footerHeight+'px'
          }

          this.footerStyObj = {
            'width':containerWidth+'px'
          }

        },
        //添加富文本标题提示
        addQuillTitle(){
          const oToolBar = document.querySelector(".ql-toolbar"),
                aButton = oToolBar.querySelectorAll("button"),
                aSelect = oToolBar.querySelectorAll("select");

                aButton.forEach(function(item){
                  if(item.className === "ql-script"){
                    item.value === "sub" ? (item.title="下标") : (item.title="上标")
                  }else if(item.className === "ql-indent"){
                    item.value === "+1" ? (item.title="向右缩进") : (item.title="向左缩进")
                  }else{
                    item.title = titleConfig[item.classList[0]];
                  }
                });

                aSelect.forEach(function(item){
                  item.parentNode.title = titleConfig[item.classList[0]];
                });
        },
        //初始化自定义按钮
        initButton(){
          //alert(123456)
          const customImage = document.querySelector('.ql-customImage');

          //customImage.style.cssText = "width:65px; border:1px solid #ccc; border-radius:5px;font-size: 12px;";
          customImage.innerHTML="<i class=\"icon iconfont ipc-add-image\"></i>";

        },
        //选择图片模态框关闭
        uploadDialogClose(){
          this.uploadDialogVisible = false;
        },
        //上传图片成功后点击确定插入图片到富文本
        insertImgToContent(imgs){
          //this.$refs.myQuillEditor.quill.getSelection()
          //获取光标位置对象，里面有两个属性，一个是index,还有个是length,这里要用range.index,即当前光标之前的内容长度，然后利用insertEmbed(length,'image',imageUrl),插入图片即可
          //this.addRange = this.$refs.myQuillEditor.quill.getSelection();
          let quill = this.$refs.myQuillEditor.quill;
          for(var i=0;i<imgs.length;i++){
            imgs[i]['selected'] = false;
            if(imgs[i]['selectIndex']){
              delete imgs[i]['selectIndex']
            }

            let length = quill.selection.savedRange.index;
            quill.insertEmbed(length !== null ? length : 0,'ipcImage',imgs[i].url,Quill.sources.USER)
          }

          //将插入的图片推入缓存去
          this.cacheImgs = this.cacheImgs.concat(imgs);
          //关闭模态框
          this.uploadDialogVisible = false;
        },
        //选择缩略图
        thumSelectItemClick(item){
          item.selected = !item.selected;
        },
        //关闭选择缩略图模态框
        thumDialogClose(){
          this.thumDialog = false;
        },
        //确认选择的缩略图
        thumSelectConfirm(imgs){
          //1.判断单图or三图
          //循环缓存图片列表cacheImgs，筛选出已选择的图片
          //推入到缩略图选择列表saveThumId
          var select_arr = [];
          for(var i=0;i<imgs.length;i++){
            select_arr.push(imgs[i].fileId)
          }

          this.saveThumId = select_arr;
        },
        onEditorReady(editor) { // 准备编辑器
 
        },
        onEditorBlur(){}, // 失去焦点事件
        onEditorFocus(){}, // 获得焦点事件
        onEditorChange(){}, // 内容改变事件

        //封面图数量更改
        thumNumChange(value){
          this.setting.cover = value;
          if(value == 1){
            if(this.saveThumId.length < 1){
              this.saveThumId = [''];
            }
          }else if(value == 2){
            if(this.saveThumId.length < 3){
              for(let i=0;i<3;i++){

                if(typeof this.saveThumId[i] === 'undefined'){
                  this.saveThumId[i] = ''
                }
              }
            }
          }

          this.$forceUpdate();
          /*this.setting.cover = value;
          if(value == 1){
            if(!this.saveThumId[0]){
              this.saveThumId = [''];
            }
          }else if(value == 2){
            var temp_arr = [];
            for(var i=0;i<3;i++){
              if(this.saveThumId[i]){
                temp_arr.push(this.saveThumId[i])
              }else{
                temp_arr.push('')
              }
            }
            this.saveThumId = temp_arr;
          }else if(value == 3){
            this.saveThumId = [];
          }*/

        },
        //投放广告
        advsChange(value){
          this.setting.advertising = value;
        },
        //付费方式
        saleTypeChange(value){
          this.setting.saleWay = value;
        },
        //获取文章分类
        getArticleCata(){
          getList(1, 999).then(res => {
            this.articleCata = res.data.data;
          });
        },
        //验证保存的文章信息
        validateArticle(){
            //标题不能为空
            if(String(this.setting.title).trim().length == 0){
              this.$message({
                message:"文章标题不能为空",
                type:"error"
              })
              return false;
            }

            //文章内容验证
            if(String(this.setting.content).trim().length == 0){
              this.$message({
                message:"文章内容不能为空",
                type:"error"
              })
              return false;
            }

            //文章分类验证
            if(String(this.setting.categoryId).trim().length == 0){
              this.$message({
                message:"请选择文章分类",
                type:"error"
              })
              return false;
            }

            //文章分类验证
            if(this.setting.advertising < 0){
              this.$message({
                message:"请选择是否投放广告",
                type:"error"
              })
              return false;
            }

            //广告投放验证
            if(this.setting.cover < 0){
              this.$message({
                message:"请选择封面",
                type:"error"
              })
              return false;
            }

            return true;
        },
        //保存处理数据
        saveHandler(status){
          //验证发布信息
          if(!this.validateArticle()){
              return false;
          }

          //设置保存状态
          this.setting.status = status;
          
          //处理定时发布
          if(status == 5){
            this.setTimingDialog = true;
            return;
          }

          this.save();

        },
        //获取保存的缩略图
        getThum(){
          if(this.setting.cover == 1){
            if(this.saveThumId.length == 0 || validatenull(this.saveThumId[0])){
              this.$ipcTips.error('请选择缩略图');
              return false;
            }
            return [this.saveThumId[0]]

          }else if(this.setting.cover == 2){
            for(let i=0;i<3;i++){
              if(validatenull(this.saveThumId[i])){
                this.$ipcTips.error('请选择缩略图');
                return false;
              }
            }
            return this.saveThumId.splice(0,3)

          }else {
            return [];
          }
        },
        //调用接口保存至数据库
        save(callback){
            var send = deepClone(this.setting);
            send["userId"] = this.userInfo.id;
            var thums = this.getThum();
            console.log("------保存的时候获取缩略图------")
            console.log(thums)
            if(thums === false) {return false};
            send["converIds"] = thums.join(",");
            send["updateTime"] = getNowStr();      
            save(send).then((res)=>{

                console.log("-------文章编辑返回信息----------")
                console.log(res)

                if(res.data.code == 200){
                    this.$message({
                        type: 'success',
                        message: "保存成功"
                    });

                    //清空当前内容
                    this.setting = this.defaultSetting;

                    //如果有回调，调用回调
                    if(callback && typeof callback == 'function'){
                      callback(res.data.data)
                    }

                }else{
                    this.$message({
                        type: 'error',
                        message: "保存失败"
                    });
                }
            })
        },
        //保存并预览
        savePreview(status){
          var _this = this;
          //验证发布信息
          if(!this.validateArticle()){
              return false;
          }
          //设置保存状态
          this.setting.status = status;
          this.save(function(articleId){
            //跳转预览
            _this.$router.push({
              path:`/content/detail/${articleId}`
            })
          });
        },
        //选择缩略图
        selectThum(){
          this.thumDialog = true;
        },
        //取消发布时间
        publishTimeCancel(val){
          this.setting.publishTime = val;
          this.setTimingDialog = false;
        },
        //确认发布时间
        publishTimeComfirm(val){
          this.setting.publishTime = val;
          this.setTimingDialog = false;
          this.save();

        },
        //选择缩略图模态框关闭
        thumSelectClose(){
          this.thumDialog = false;
        }
    },
    computed: {
        editor() {
            return this.$refs.myQuillEditor.quill;
        },
    }
}
</script>


<style>
  .content-component__scroll{
    width: 100%;
    height: 100%;
    
  }
  .content-component__scroll .el-scrollbar__wrap{
    overflow-x: auto;
  }


  /*设置富文本高度*/
  .ql-editor{
    height:350px;
    line-height: 2;
  }

  .ql-editor.ql-blank::before {
    font-style: normal;
    font-size: 16px;
    line-height: 25px;
    color: #999;
    
  }

  .ql-snow .ql-editor img {
    max-width: 440px;
  }

  .setting-form .el-input{
    width: 200px;
  }

  .article-title{
    font-family: PingFangSC-Regular,Arial;
    min-height: 36px;
    font-weight: 700;
    font-size: 24px;
    line-height: 36px;
    color: #222;
    padding: 10px 0;
    background-color: transparent;
  }

  .article-title .el-input__inner{
    border-width: 0;
  }

  .img-upload-input .el-upload--picture-card{
    width: 100%;
    height: 100%;
    line-height: 180px;
  }
</style>


<style scoped>
  .rich-text-wrap{
    margin-top: 20px;
    padding: 0 20px;
  }

  .rich-text{
    position: relative;
    padding-bottom: 30px;
  }
  

  .article-setting-wrap{
    margin-top: 30px;
    padding: 0 20px;
  }

  .setting-form{
    width: 100%;
  }

  .footer{
    /*position: fixed;
    bottom: 0px;*/
    padding: 20px 40px;
    border-top: 1px solid rgb(232, 232, 232);
    z-index: 0;
    background-color: white;
    text-align: right;
    width: 100%;
  }


  /*添加缩略图按钮*/
  .thum-wrap{
    overflow: hidden;
  }
  .thum-item{
    width: 150px;
    height: 105px;
    border: 1px solid #e8e8e8;
    background-color: #f0f1f3;
    display: flex;
    justify-content: center;
    align-items: center;
    float: left;
    margin-right: 15px;
  }

  .thum-item .el-icon-plus{
    font-size: 30px;
    color: #ccc;

  }

  .thum-item img{
    width: 100%;
    height: 100%;
  }



</style>



<style lang="scss" scoped>
.content {
  &-container {
    height: 100%;
  }
  
}

</style>
